const router = require('koa-router')()
const lotteryDao = require('../dao/lotteryDao')
const $util = require('../util/util')
const WECHAT = require('../util/wechat')
const CONFIG = require('../util/util.config') // 配置地址文件

router.post('/test', async (ctx) => {
  // let cookie = ctx.cookies.get('openid')
  console.log(ctx.request.xml, ctx.request.body)
  ctx.body = 1
})

// 用户是否赞赏过
router.get('/lottery/api/v1/is_user_pay_forecast', async (ctx, next) => {
 // console.log('req',req.query)
  ctx.query.userId = ctx.cookies.get('userId')
  let ret = await lotteryDao.isUserPayForecast(ctx.query)

  if (Object.keys(ret).length) {
    ctx.body = $util.jsonWrite(ret, {
      flag: true,
      msg: '已支付'
    })
  } else {
    ctx.body = $util.jsonWrite(ret, {
      flag: false,
      msg: '未支付'
    })
  }
})

// 添加预测页面日志
router.get('/lottery/api/v1/createUserForecastLog', async (ctx, next) => {
  ctx.body = {
    status: true,
    data: null,
    msg: '添加日志成功'
  }

 // 更新阅读量
  setTimeout(function () {
    lotteryDao.updateForecastRead(ctx.query)
    lotteryDao.createForecastLog(ctx.query)
  }, 10000)
})

// 微信支付回调
router.post('/forecast/api/v1/pay', async (ctx, next) => {
 // 支付结果通用: 来源是微信
  console.log(ctx.request.body, ctx.request.type)
  var xml = ctx.request.body.xml
  // console.log(xml)

 // 如果成功数据入库，失败的话可能需要退款
  if (xml.result_code && xml.return_code) {
    xml.status = 1
 // 查询交易数据：作者id，和交易额度
    let res = await lotteryDao.queryByOutTradeNo(xml)
    console.log(res)
    let money = res.total_fee
    let taxFee = Math.round(money * 0.1)
    let addMoney = +money - taxFee
  // 更新支付记录表
    setTimeout(() => {
      lotteryDao.updateAccountMoney({
        add_money: addMoney,
        writer_id: res.get_user_id
      })
      lotteryDao.updateForecastRecognizedNum(res) // 更新彩票预测的认可数值
      lotteryDao.updateMediaService(res)
    }, 500)

    lotteryDao.updateTransaction(xml) // 更新交易记录数据
    ctx.body = `<xml>
    <return_code><![CDATA[SUCCESS]]></return_code>
    <return_msg><![CDATA[OK]]></return_msg>
    </xml>`
  }
})

// 预测观点发起微信支付
router.get('/lottery/api/v1/forecast_request_pay', async (ctx, next) => {
  let [_appid, mchId, key, _deviceInfo] = [CONFIG.appid, CONFIG.mch_id, CONFIG.app_key, 'WEB']
  let _body = '椰子观点'
  let _nonceStr = await WECHAT.randomString(32) // 随机数
  let ip = ctx.headers['x-forwarded-for'] || ctx.connection.remoteAddress || ctx.socket.remoteAddress || ctx.connection.socket.remoteAddress
  let money = Math.round(+ctx.query.money * 1e20 / 1e18)
  let taxFee = Math.round(money * 0.1)
  console.log(`增加的金额${money - taxFee}`)
  let tradeNo = parseInt(new Date().getTime() / 1000) + await WECHAT.randomString(21) + ''
  console.log('tradeNo:', tradeNo)
  // 获取签名
  const opts = {
    appid: _appid,
    mch_id: mchId,
    device_info: _deviceInfo,
    nonce_str: _nonceStr,
    body: _body,
    out_trade_no: tradeNo,
    total_fee: money,
    spbill_create_ip: ip, // 终端IP
    notify_url: CONFIG.notify_url,
    trade_type: 'JSAPI',
    openid: ctx.cookies.get('openid')
  }
  let _sign = await WECHAT.paysign(opts, key)  // 通过签名算法计算得出的签名值

  // 预支付交易单:预支付id
  opts.sign = _sign
  opts.sign_type = 'MD5'
  let rep = await WECHAT.prePay(opts)
  console.log('prepay_id:' + rep.prepay_id)

 // 再次签名
  const resTime = String(parseInt(new Date().getTime() / 1000))
  const nonceStr = await WECHAT.randomString(32)
  const secondOpts = {
    appId: _appid,
    timeStamp: resTime,
    nonceStr: nonceStr,
    package: 'prepay_id=' + rep.prepay_id,
    signType: 'MD5'
  }
  let paySign = await WECHAT.paysign(secondOpts, key) // create paySign
  secondOpts.paySign = paySign
  secondOpts.prepayId = rep.prepay_id

  ctx.body = {
    status: true,
    data: secondOpts,
    msg: '微信预支付成功'
  }

 // 交易记录入库
  let transaction = {
    user_id: ctx.cookies.get('userId'),
    openid: ctx.cookies.get('openid'),
    total_fee: money,
    tax_fee: taxFee,
    out_trade_no: tradeNo,
    status: 0,
    forecast_id: ctx.query.forecast_id,
    prepay_id: secondOpts.prepayId,
    getUserId: ctx.query.getUserId
  }
    // 预交易记录入库,
  lotteryDao.insertTransactionAndForecastId(transaction)
})

// base 获取用户opneid和unionid；流程需要更改
router.get('/lottery/api/v1/getUserOpenid', async (ctx, next) => {
 // 是否有openid，没有,插入数据库,有取出id
  let userInfo = await $util.getWechatOpenid(ctx.query)
  if (typeof userInfo.openid !== 'undefined') {
    let userId = await lotteryDao.isUserInfoBaseSaveinWriter(userInfo)
    userInfo.userId = userId
    ctx.body = {
      status: true,
      data: userInfo,
      msg: '获取到了用户的openid'
    }
  } else {
    ctx.body = {
      status: false,
      data: null,
      msg: '获取到了用户的openid失败'
    }
  }
})
// 获取用户信息
router.get('/lottery/api/v1/snsapiUserOpenid', async (ctx, next) => {
  let snsapiUserinfo = await $util.getWechatOpenid(ctx.query)
  if (typeof snsapiUserinfo.openid !== 'undefined') {
    console.log('snsapiUserinfo:', snsapiUserinfo)
    let userInfo = await $util.getWexinUserInfo(snsapiUserinfo)
    let userId = await lotteryDao.isUserInfoSaveinWriter(userInfo)
    console.log('userId:', userId)
    userInfo.userId = userId
    ctx.body = {
      status: true,
      data: userInfo,
      msg: '获取到了用户的基本信息'
    }
  } else {
    ctx.body = {
      status: false,
      data: null,
      msg: '获取到了用户的openid失败'
    }
  }
})

// 获取预测的数据
router.get('/lottery/api/v1/get_forecast_info', async (ctx, next) => {
  let ret = await lotteryDao.getForecastInfo(ctx.query)

  ctx.body = $util.jsonWrite(ret[0], {
    flag: true,
    msg: '获取预测数据成功'
  })
})

// 获取媒体账号的信息
router.get('/lottery/api/v1/get_media_info_by_id', async (ctx, next) => {
  let ret = await lotteryDao.getMediaInfoBymediaId(ctx.query)

  ctx.body = $util.jsonWrite(ret[0], {
    flag: true,
    msg: '存在媒体信息'
  })
})

// 获取根据排名的预测观点列表
router.get('/lottery/api/v1/get_forecast_list_option', async (ctx, next) => {
  // console.log(ctx.query)
  ctx.query.timeString = await $util.dateFormat(Date.now() - 1.5 * 24 * 60 * 60 * 1000, 0)
  let ret = await lotteryDao.getForecastListOption(ctx.query)
  if (ret) {
    ctx.body = {
      status: true,
      data: ret,
      page: ret.length,
      msg: '请求成功'
    }
  } else {
    ctx.body = {
      status: false,
      data: ret,
      page: ret.length,
      msg: 'no data'
    }
  }
})

// 获取作者id获取该作者预测观点列表,取最近的50条记录
router.get('/lottery/api/v1/get_forecast_list_by_media_id', async (ctx, next) => {
  // console.log(ctx.query)
  ctx.query.timeString = await $util.dateFormat(Date.now() - 1.5 * 24 * 60 * 60 * 1000, 0)
  let ret = await lotteryDao.getForecastListByMediaId(ctx.query)
  if (ret) {
    ctx.body = {
      status: true,
      data: ret,
      page: ret.length,
      msg: '请求成功'
    }
  } else {
    ctx.body = {
      status: false,
      data: ret,
      page: ret.length,
      msg: 'no data'
    }
  }
})

// 获取
module.exports = router
